<template>
  <div class="map-container">
    <!-- 搜索区域 -->
    <div class="search-box">
      <div class="input-group">
        <label class="station-label">出发站:</label>
        <input
            v-model="startStation"
            type="text"
            placeholder="请输入出发站"
            class="station-input"
            @keyup.enter="searchRoute"
        />
      </div>

      <div class="input-group">
        <label class="station-label">到达站:</label>
        <input
            v-model="endStation"
            type="text"
            placeholder="请输入到达站"
            class="station-input"
            @keyup.enter="searchRoute"
        />
      </div>

      <div class="route-options">
        <label class="option-label">路线类型:</label>
        <select v-model="routeType" class="route-select">
          <option value="driving">驾车</option>
          <option value="transit">公交</option>
        </select>

        <button @click="searchRoute" class="search-btn">
          <i class="fas fa-search"></i> 规划路线
        </button>

        <button @click="clearRoute" class="clear-btn" v-if="routePlanned">
          <i class="fas fa-trash"></i> 清除路线
        </button>
      </div>
    </div>

    <!-- 状态提示 -->
    <div class="status-message" v-if="statusMessage">
      {{ statusMessage }}
    </div>

    <!-- 地图容器 -->
    <div id="map" class="map-content"></div>

    <!-- 路线信息面板 - 仅保留距离 -->
    <div class="route-info" v-if="routeDistance && routePlanned">
      <h3>路线信息</h3>
      <p><i class="fas fa-route"></i> 距离: {{ routeDistance }}</p>
    </div>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref, watch } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";

// 地图实例相关
let map = null;
let AMap = null;
let geocoder = null;
let routePlanner = null;

// 响应式数据 - 仅保留距离相关
const startStation = ref("");
const endStation = ref("");
const routeType = ref("driving"); // 默认驾车路线
const statusMessage = ref("");
const routePlanned = ref(false);
const routeDistance = ref(""); // 仅存储距离信息
const markers = ref([]); // 存储标记点，用于清除
const previousRoute = ref(null); // 存储上一条路线，用于清除

// 初始化地图
onMounted(() => {
  // 配置安全密钥
  window._AMapSecurityConfig = {
    securityJsCode: "6a467c8f01ff11c98e910a71630da2db",
  };

  // 加载高德地图
  AMapLoader.load({
    key: "285907a220804b186a76285bbf95f08b", // 你的高德地图Key
    version: "2.0",
    plugins: [
      "AMap.Scale",       // 比例尺
      "AMap.Geocoder",    // 地理编码
      "AMap.Driving",     // 驾车路线
      "AMap.Transfer"     // 公交路线
    ],
  })
      .then((loadedAMap) => {
        AMap = loadedAMap;

        // 初始化地图
        map = new AMap.Map("map", {
          viewMode: "3D",
          zoom: 11,
          center: [116.397428, 39.90923], // 默认北京
          resizeEnable: true
        });

        // 添加比例尺控件
        map.addControl(new AMap.Scale());

        // 初始化地理编码器
        geocoder = new AMap.Geocoder({
          city: "", // 城市，默认全国
          radius: 1000 // 范围，默认1000米
        });

        statusMessage.value = "地图加载完成，请输入出发站和到达站";
      })
      .catch((e) => {
        console.error("地图加载失败:", e);
        statusMessage.value = "地图加载失败，请刷新页面重试";
      });
});

// 清理资源
onUnmounted(() => {
  if (map) {
    map.destroy();
  }
  map = null;
  AMap = null;
  geocoder = null;
  routePlanner = null;
});

// 监听路线类型变化，重新规划路线  驾车<->公交
watch(routeType, (newVal) => {
  if (routePlanned.value && startStation.value && endStation.value) {
    searchRoute();
  }
});

// 规划路线
const searchRoute = () => {
  // 验证输入
  if (!startStation.value.trim() || !endStation.value.trim()) {
    statusMessage.value = "请输入出发站和到达站";
    return;
  }

  // 清除之前的路线和标记
  clearRoute();

  statusMessage.value = "正在解析地址...";

  // 解析出发站地址
  geocoder.getLocation(startStation.value.trim(), (status, result) => {
    if (status === "complete" && result.geocodes.length > 0) {
      const startPoint = result.geocodes[0].location;
      const startAddress = result.geocodes[0].formattedAddress;

      // 解析到达站地址
      geocoder.getLocation(endStation.value.trim(), (status2, result2) => {
        if (status2 === "complete" && result2.geocodes.length > 0) {
          const endPoint = result2.geocodes[0].location;
          const endAddress = result2.geocodes[0].formattedAddress;

          // 添加标记点
          addMarker(startPoint, "start", startAddress);
          addMarker(endPoint, "end", endAddress);

          // 规划路线
          planRoute(startPoint, endPoint);

          // 调整地图视野，显示全路线
          map.setFitView(markers.value);

        } else {
          statusMessage.value = "到达站地址解析失败，请检查输入";
          console.error("到达站解析失败:", result2);
        }
      });
    } else {
      statusMessage.value = "出发站地址解析失败，请检查输入";
      console.error("出发站解析失败:", result);
    }
  });
};

// 添加标记点
const addMarker = (position, type, address) => {
  const icon = new AMap.Icon({
    size: new AMap.Size(32, 32),
    image: type === "start"
        ? "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png"
        : "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png",
    imageSize: new AMap.Size(32, 32)
  });

  const marker = new AMap.Marker({
    position: position,
    icon: icon,
    title: address,
    anchor: "bottom-center"
  });

  marker.setMap(map);
  markers.value.push(marker);
};

// 规划路线（仅处理距离信息）
const planRoute = (start, end) => {
  const routeTypeName = routeType.value === "driving" ? "驾车" : "公交";
  statusMessage.value = `正在规划${routeTypeName}路线...`;

  // 清除之前的路线规划器
  if (routePlanner) {
    routePlanner = null;
  }

  // 根据路线类型创建对应的规划器
  if (routeType.value === "driving") {
    routePlanner = new AMap.Driving({
      map: map,
      panel: false,
      lineOptions: {
        strokeColor: "#3366FF",
        strokeWeight: 5
      }
    });
  } else if (routeType.value === "transit") {
    // 公交路线需要指定城市
    const city = start.lng.toFixed(6) + "," + start.lat.toFixed(6);
    routePlanner = new AMap.Transfer({
      map: map,
      panel: false,
      city: city,
      policy: AMap.TransferPolicy.LEAST_TIME,
      lineOptions: {
        strokeColor: "#FA5A5A",
        strokeWeight: 5
      }
    });
  }

  // 搜索路线 - 仅提取距离信息
  const searchCallback = (status, result) => {
    if (status === "complete") {
      // 清除之前的路线
      if (previousRoute.value) {
        map.remove(previousRoute.value);
      }

      routePlanned.value = true;
      let distance = 0;
      let lineArr = [];

      // 根据路线类型解析距离
      if (routeType.value === "driving") {
        if (result.routes && result.routes.length > 0) {
          distance = result.routes[0].distance;
          lineArr = result.routes[0].path;
        }
      } else if (routeType.value === "transit") {
        if (result.plans && result.plans.length > 0) {
          distance = result.plans[0].distance;
          // 构建公交路线的坐标点数组
          result.plans[0].segments.forEach(segment => {
            if (segment.busLines && segment.busLines.length > 0) {
              lineArr.push(...segment.busLines[0].polyline.split(';')
                  .map(point => point.split(',').map(Number)));
            }
          });
        }
      }

      // 显示距离
      routeDistance.value = formatDistance(distance);

      // 手动绘制路线
      if (lineArr && lineArr.length > 0) {
        const polyline = new AMap.Polyline({
          path: lineArr,
          strokeColor: routeType.value === "driving" ? "#3366FF" : "#FA5A5A",
          strokeWeight: 5,
          strokeOpacity: 0.8
        });
        map.add(polyline);
        previousRoute.value = polyline;
      }

      statusMessage.value = "路线规划完成";
    } else {
      statusMessage.value = `路线规划失败: ${result.info || '未知错误'}`;
      console.error(`${routeTypeName}路线规划失败:`, result);
    }
  };

  // 执行路线搜索
  if (routeType.value === "transit") {
    routePlanner.search(new AMap.LngLat(start.lng, start.lat),
        new AMap.LngLat(end.lng, end.lat),
        searchCallback);
  } else {
    routePlanner.search(start, end, searchCallback);
  }
};

// 清除路线和标记
const clearRoute = () => {
  // 清除标记
  markers.value.forEach(marker => {
    marker.remove();
  });
  markers.value = [];

  // 清除路线
  if (previousRoute.value) {
    map.remove(previousRoute.value);
    previousRoute.value = null;
  }

  // 清除路线规划器
  if (routePlanner && routePlanner.clear) {
    routePlanner.clear();
  }

  // 重置状态
  routePlanned.value = false;
  routeDistance.value = "";
  statusMessage.value = "";
};

// 格式化距离显示
const formatDistance = (meters) => {
  if (meters < 1000) {
    return `${meters}米`;
  } else {
    return `${(meters / 1000).toFixed(1)}公里`;
  }
};
</script>

<style scoped>
.map-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.search-box {
  padding: 15px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.input-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.station-label {
  font-weight: 500;
  color: #333;
  min-width: 60px;
}

.station-input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  width: 200px;
  transition: border-color 0.2s;
}

.station-input:focus {
  border-color: #4285f4;
  outline: none;
  box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.2);
}

.route-options {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-left: auto;
}

.option-label {
  color: #333;
}

.route-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
  font-size: 14px;
  cursor: pointer;
}

.search-btn {
  padding: 8px 20px;
  background-color: #4285f4;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: background-color 0.2s;
}

.search-btn:hover {
  background-color: #3367d6;
}

.clear-btn {
  padding: 8px 15px;
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: background-color 0.2s;
}

.clear-btn:hover {
  background-color: #d32f2f;
}

.status-message {
  padding: 8px 15px;
  color: #666;
  background-color: #fff8e1;
  border-bottom: 1px solid #ffe082;
  font-size: 14px;
}

.map-content {
  flex: 1;
  width: 100%;
}

.route-info {
  position: absolute;
  bottom: 20px;
  right: 20px;
  background-color: white;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  max-width: 250px;
  font-size: 14px;
}

.route-info h3 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #333;
  font-size: 16px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.route-info p {
  margin: 5px 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.route-info i {
  color: #4285f4;
  width: 16px;
  text-align: center;
}

@media (max-width: 768px) {
  .search-box {
    flex-direction: column;
    align-items: stretch;
  }

  .route-options {
    margin-left: 0;
    justify-content: space-between;
  }

  .station-input {
    width: 100%;
  }

  .route-info {
    max-width: calc(100% - 40px);
    bottom: 10px;
    right: 10px;
    padding: 10px;
  }
}
</style>
